<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <!--<el-input v-model="listQuery.startTime" clearable size="mini" class="filter-item" style="width: 200px;" placeholder="请输入开始日期"/>
      <el-input v-model="listQuery.endTime" clearable size="mini" class="filter-item" style="width: 200px;" placeholder="请输入结束日期"/>-->
      <!--<div class="block">-->
      <!--<span class="demonstration"></span>-->
      <el-date-picker
        v-model="listQuery.startToEnd"
        :picker-options="pickerOptions"
        type="daterange"
        align="right"
        unlink-panels
        range-separator=" 至 "
        start-placeholder="开始日期"
        end-placeholder="结束日期"/>
      <!--</div>-->
      <el-select v-model="listQuery.batchNumber" clearable placeholder="请选择产品批号">
        <el-option
          v-for="(value, key) in batchNumbers"
          :key="key"
          :label="value"
          :value="key"/>
        <!--<el-option
          v-for="item in batchNumbers"
          :key="item.value"
          :label="item.label"
          :value="item.label">
        </el-option>-->
      </el-select>
      <!--<el-input v-model="listQuery.batchNumber" clearable size="mini" class="filter-item" style="width: 200px;" placeholder="请输入产品批号"/>-->
      <!--<el-input v-model="listQuery.batchNumber" clearable size="mini" class="filter-item" style="width: 200px;" placeholder="请输入产品批号"/>-->
      <!--  <el-input v-model="listQuery.userDepartments" clearable size="mini" class="filter-item" style="width: 200px;" placeholder="请输入使用部门"/>-->
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleNew">最新</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">新建</el-button>
      <el-button :loading="downloadLoading" class="filter-item" type="warning" icon="el-icon-download" @click="handleDownload">导出</el-button>

      <!--<el-upload class="upload-demo" action="http://139.159.147.237:8005/act/insert" :on-success="handleExcelSuccess" :on-remove="handleRemove" :before-remove="beforeRemove" :limit="1" :file-list="fileList" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel, .xlsx">
        <el-button type="primary">
          选择文件
          <i class="el-icon-upload el-icon&#45;&#45;right"></i>
        </el-button>
      </el-upload>-->
      <!--<el-table v-if="list.length" :data="list" style="width: 100%">
        <el-table-column prop="num" label="序号" width="100" />
        <el-table-column prop="names" label="名称" width="200" />
        <el-table-column prop="links" label="链接" width="200" />
        <el-table-column prop="passwords" label="密码" />
      </el-table>
      <el-pagination class="page" v-if="list.length" layout="prev, pager, next" :total="20" />-->
      <!--<el-upload
        style="display: inline"
        :show-file-list="false"
        :on-success="onSuccess"
        :on-error="onError"
        :before-upload="beforeUpload"
        action="/demo/admin/productProduction/insertMany">
        <el-button size="mini" type="success"  :icon="uploadBtnIcon">导入</el-button>
      </el-upload>-->
      <!--<input type="file" ref="myfile">-->
      <!--<el-button @click="importData" type="success" size="mini" icon="el-icon-upload2">导入数据</el-button>-->
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" size="small" element-loading-text="正在查询中。。。" border fit highlight-current-row @sort-change="handleSortChange">

      <!--<el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" class="table-expand">
            <el-form-item label="测量活度">
              <span>{{ props.row.oralConcentration }}</span>
            </el-form-item>
            <el-form-item label="剩余活度">
              <span>{{ props.row.remainActivity }}</span>
            </el-form-item>
            <el-form-item label="剩余体积">
              <span>{{ props.row.remainVolume }}</span>
            </el-form-item>
            <el-form-item label="生产日期">
              <span>{{ props.row.productionDate }}</span>
            </el-form-item>
            <el-form-item label="原料批号">
              <span>{{ props.row.rawNumber1 }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>-->

      <el-table-column align="center" min-width="70" label="序号" prop="id" sortable/>
      <el-table-column align="center" min-width="100" label="产品名称" prop="name" />
      <!--<el-table-column align="center" min-width="90" label="产品批号" prop="date" />-->
<!--      <el-table-column align="center" min-width="90" label="规格" prop="specifications"/>-->
      <el-table-column align="center" min-width="100" label="生产单位/地址" prop="productionAddress" />
      <el-table-column align="center" min-width="100" label="出厂活度" prop="dispatchActivity" />
      <el-table-column align="center" min-width="100" label="使用活度" prop="calibrationActivity" />
      <!--<el-table-column align="center" min-width="200" label="检定单位" prop="verfier" />-->
      <!--<el-table-column align="center" min-width="200" label="证书编号" prop="vertificateNo" />-->
      <el-table-column align="center" min-width="100" label="产品批号" prop="batchNumber"/>
      <!--<el-table-column align="center" min-width="200" label="是否有效" prop="isEffective" />-->
      <el-table-column align="center" min-width="80" label="毫居/居里" prop="unit"/>
      <el-table-column align="center" min-width="140" label="总活度" prop="totalActivity"/>
      <el-table-column align="center" min-width="140" label="件数" prop="pieces" />
      <el-table-column align="center" min-width="90" label="购进日期" prop="purchaseDate" />
      <el-table-column align="center" min-width="80" label="高浓id" prop="gaolongId" />
      <el-table-column align="center" min-width="80" label="口服液id" prop="solutionId" />
      <el-table-column align="center" min-width="140" label="备注" prop="notes" />


      <el-table-column align="center" label="操作" width="150" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate2(scope.row)">编辑</el-button>
          <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-tooltip placement="top" content="返回顶部">
      <back-to-top :visibility-height="100" />
    </el-tooltip>

  </div>
</template>

<style>
	.el-dialog {
    width: 60%;
	}
  .table-expand {
    font-size: 0;
  }
  .table-expand label {
    width: 100px;
    color: #99a9bf;
  }
  .table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
  }
  .gallery {
    width: 80px;
    margin-right: 10px;
  }
</style>

<script>

import { listBachNumbers, listproductProductions, deleteProductProductions, insertAllproductProduction, publishproductProduction, getSortedList, listByOrders,listBachNumbers2} from '@/api/business/productProduction'
import BackToTop from '@/components/BackToTop'
import { listIoralRaw, listReportForms} from '@/api/business/ioralRaw'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import axios from 'axios'
export const uploadFileRequest = (url, params) => {
  return axios({
    method: 'post',
    url: '/productProduction/insertMany',
    data: params,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}
export default {
  name: 'ProductProductionList',
  components: { BackToTop, Pagination },
  filters: {

  },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      value1: '',
      value2: '',
      loading: false,
      date: new Date(),
      files: [],
      newAttachmentsTable: [],
      insert: true,
      noPersonalInformation: [],
      listQuery: {
        page: 1,
        limit: 20,
        batchNumber: '',
        startToEnd: [],
        sort: 'purchase_date',
        order: 'desc',
        isNew:0
      },
      batchQuery: {

        batchNumber: '',
        startToEnd: [],
        sort: 'measure_tine',
        order: 'desc',
        isNew: 0
      },
      batchNumbers: [],
      productProductionDetail: '',
      detailDialogVisible: false,
      downloadLoading: false,
      btnText: ''
    }
  },
  created() {
    this.getList()
    this.getBatchNumbers()
  },
  methods: {
    importData() {
      const myfile = this.$refs.myfile
      const files = myfile.files
      const file = files[0]
      var formData = new FormData()
      formData.append('file', file)
      this.uploadFileRequest('/admin/demo/productProduction/insertMany', formData).then(resp => {
        if (resp) {
          console.log(resp)
        }
      })
    },
    handleSortChange({ name, order }) {
      this.listLoading = true
      if (order === 'ascending') {
        console.log(name)
        this.listQuery.sort = name
        this.listQuery.order = 'asc'
        listByOrders(this.listQuery).then(response => {
          this.list = response.data.data.items
          this.total = response.data.data.total
          this.listLoading = false
        })
        /* this.tableData.sort((a, b) => a[prop] > b[prop] ? 1 : -1);*/
      } else if (order === 'descending') {
        /* this.tableData.sort((a, b) => a[prop] < b[prop] ? 1 : -1);*/
        console.log(name)
        this.listQuery.sort = name
        this.listQuery.order = 'desc'
        listproductProductions(this.listQuery).then(response => {
          this.list = response.data.data.items
          this.total = response.data.data.total
          this.listLoading = false
        })
      } else {
        // 如果需要重置排序，可以重新获取数据或使用原始数据填充tableData
      }
    },
    fetchSortedData(sortField, sortOrder) {
      /* axios.get('/api/data/sort', { params: { sortField, sortOrder } })*/
      getSortedList(sortField, sortOrder).then(response => {
        this.list = response.data.data.items // 更新表格数据
      })
        .catch(error => {
          console.error('Error fetching sorted data:', error)
        })
    },
    getList() {
      this.listLoading = true
      listIoralRaw(this.listQuery).then(response => {
        this.list = response.data.data.items
        this.total = response.data.data.total
        this.listLoading = false
      }).catch(() => {
        this.list = []
        this.total = 0
        this.listLoading = false
      })
    },
    onSuccess(response, file, fileList) {
      this.enabledUploadBtn = true
      this.files = fileList
      this.uploadBtnIcon = 'el-icon-upload2'
      this.btnText = '数据导入'
      insertAllproductProduction(data).then(response => {
        this.$notify.success({
          title: '成功',
          message: '创建成功'
        })
        this.$router.push({ path: '/productProduction/list' })
      }).catch(response => {
        MessageBox.alert('业务错误：' + response.data.errmsg, '警告', {
          confirmButtonText: '确定',
          type: 'error'
        })
      })
    },
    getBatchNumbers() {
      listBachNumbers2(this.listQuery).then(response => {
        this.batchNumbers = response.data.data.batchNumbers/* .sort((a, b) => new Date(a) - new Date(b))*/
        /*  this.batchNumbers2=this.batchNumbers.sort((a, b) => new Date(a) - new Date(b))*/
      }).catch(() => {
        console.log('getList catch')
        /* this.listStockss = []
        /!*this.total1 = 0*!/
        this.listLoading = false*/
      })
    },
    /* importData() {
      let myfile = this.$refs.myfile;
      let files = myfile.files;
      let file = files[0];
      const formData = new FormData()
      formData.append("file", file);
      this.uploadFileRequest("/productProduction/insertMany",formData).then(resp=>{
        if (resp) {
          console.log(resp);
        }
      })
    },*/
    /*   onError(err, file, fileList) {
      this.enabledUploadBtn = true;
      this.uplo<el-table-column align="center" min-width="200" label="剩余量" prop="remainQuantity" />adBtnIcon = 'el-icon-upload2';
      this.btnText = '数据导入';
    },*/
    beforeUpload(file) {
      this.enabledUploadBtn = false
      this.uploadBtnIcon = 'el-icon-loading'
      this.btnText = '正在导入'
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleNew() {
      this.listQuery.page = 1
      this.listQuery.isNew = 1
      this.getList()
    },
    handleCreate() {
      this.$router.push({ path: '/iorders/createIoralRaw' })
    },
    handleUpdate2(row) {
      this.$router.push({ path: '/iorders/editIoralRaw', query: { id: row.id }})
    },
    handleUpdate(row) {
      this.$router.push({ path: '/productProduction/update', query: { id: row.id }})
    },
    showDetail(detail) {
      this.productProductionDetail = detail
      this.detailDialogVisible = true
    },

    handleDelete(row) {
      deleteProductProductions(row).then(response => {
        this.$notify.success({
          title: '成功',
          message: '删除成功'
        })
        const index = this.list.indexOf(row)
        this.list.splice(index, 1)
      }).catch(response => {
        this.$notify.error({
          title: '失败',
          message: response.data.errmsg
        })
      })
    },
    handleDownload() {
      this.downloadLoading = true

      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['序号', '产品批号', '原料批号1', '原料批号2', '核素浓度', '生产日期', '测量时间', '口服液浓度', '核素取样时间', '产品取样时间', '取样人', '产品生产体积', '产品活度', '剩余活度', '剩余体积']
        const filterVal = ['id', 'batchNumber', 'rawNumber1', 'rawNumber2', 'rawConcentration', 'productionDate', 'measureTine', 'oralConcentration', 'rawSampleTime', 'oralSampleTime', 'measureTime', 'sampler', 'productCapacity', 'productActivity', 'productActivity', 'productActivity']
        excel.export_json_to_excel2(tHeader, this.list, filterVal, '碘131化钠口服溶液生产信息表')
        this.downloadLoading = false
      })
    }
  }
}
</script>
